<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 使用导入的页面工具栏组件 -->
      <PageTools>
        <!-- 左侧结构 -->
        <template #slot-left>
          <span>共19条数据</span>
        </template>
        <!-- 右侧结构 -->
        <template #slot-right>
          <!-- v-power 自定义指令 -->
          <el-button v-power="'import'" type="danger" size="small" @click="$router.push('/excel')">导入Excel</el-button>
          <el-button v-power="'export'" type="success" size="small" @click="downLoadExcel">导出Excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 表格区域 -->
      <el-card style="margin-top: 10px;" :default-sort="{prop: 'workNumber'}">
        <el-table border :data="employeesList">
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column label="头像" width="120px">
            <template slot-scope="scope">
              <!-- <img :src="scope.row.staffPhoto" alt="" class="staffPhoto"> -->
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" />
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column prop="formOfEmployment" label="聘用形式" :formatter="formatter" />
          <el-table-column prop="departmentName" label="部门" />
          <!-- 把入职时间写成作用域插槽 -->
          <el-table-column label="入职时间" sortable>
            <template slot-scope="scope">
              <span> {{ scope.row.timeOfEntry | dayTime }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="formOfEmployment" label="账户状态" :formatter="formatter" />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="setRole(scope.row)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmp(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <!-- 添加员工弹框组件 第一遍 -->
        <el-dialog title="添加员工" :visible.sync="showDialog" width="50%" :close-on-click-modal="false" :close-on-press-escape="false" @close="resetForm">
          <empDialog ref="addForm" @closeDialog="showDialog=false" @updataDialog="updataDialog" />
        </el-dialog>
        <!-- 分配角色弹框 -->
        <el-dialog title="角色管理" :visible.sync="showRoleDialog" width="50%" :close-on-click-modal="false" :close-on-press-escape="false">
          <AssignRole v-if="showRoleDialog" :user-id="userId" @closeRoleDialog="closeRoleDialog" />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// 存在bug,聘用形式在控制台显示字符串不是数字类型
import empDialog from './empDialog.vue'
import { getEmployeesList, delEmployees } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import dayjs from 'dayjs'
import AssignRole from './assignRole.vue'
export default {
  name: 'Employees',
  components: {
    empDialog,
    AssignRole
  },
  // 格式化时间
  filters: {
    dayTime(value) {
      return dayjs(value).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1,
        size: 10
      },
      employeesList: [],
      total: 0,
      showDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    // 调用获取员工列表方法
    this.getEmployeesList()
  },
  methods: {
    // 子组件派发事件,确认分配角色后,关闭弹框
    closeRoleDialog() {
      this.showRoleDialog = false
    },
    // 展示分配角色组件
    setRole(row) {
      this.userId = row.id || row._id
      this.showRoleDialog = true
    },
    // 定义一个转换格式的样式
    transExcel(rows) {
      // 1.声明好枚举数据
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 2.通过Object.keys(),获取到rows第一对象中所有的英文key
      const headerKey = Object.keys(rows[0])
      // 3. 根据枚举数据,获取到英文key对应的中文key
      const header = headerKey.map(item => {
        return map[item]
      })
      // 4.获取到英文key对应的value
      const data = rows.map(data => {
        return Object.values(data)
      })
      return { header, data }
    },
    // 导出Excel
    async downLoadExcel() {
      // 获取到最新的员工列表数据
      const res = await getEmployeesList(this.query)
      // console.log(res)
      const { header, data } = this.transExcel(res.data.rows)
      // 这个写法 是按需导入
      // 参数excel 代表 Export2Excel.js这个文件导出的方法
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: header, // 表头
          data: data, // 导出的格式化以后的数据
          filename: '人资项目员工列表', // 导入的Excel文件的名称
          autoWidth: true, // Excel单元和宽度自适应
          bookType: 'xlsx' // 导入的Excel类型
        })
      })
    },
    // 弹框消失,表单重置
    resetForm() {
      this.$refs.addForm.resetForm()
    },
    // 点击新增员工,弹框消失,重新获取数据 区别于点击取消不发起请求
    updataDialog() {
      this.showDialog = false
      this.getEmployeesList()
    },
    // 删除用户信息
    async delEmp(id) {
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(async err => err)
      // console.log(confirmRes)
      if (confirmRes === 'confirmRes') return this.$message('您已取消删除')
      const res = await delEmployees(id)
      if (this.employeesList.length === 1) {
        this.query.page--
        if (this.query.page < 1) {
          this.query.page = 1
        }
      }
      this.$message.success(res.message)
      this.getEmployeesList()
    },
    // 格式化聘用形式--枚举 后台返给我们的数据是字符串类型的,需要在这里转换一个数据形式
    formatter(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === Number(cellValue))
      if (obj) {
        return obj.value
      } else {
        return '未知'
      }
    },
    // 获取员工列表
    async getEmployeesList() {
      const res = await getEmployeesList(this.query)
      // console.log(res)
      this.employeesList = res.data.rows
      this.total = res.data.total
    },
    // 每页条数发生变化触发的函数
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeesList()
    },
    // 页码发生变化触发的函数
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeesList()
    }
  }
}
</script>

<style lang="scss" scoped>
.staffPhoto {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

 ::v-deep .el-image {
    width: 100px;
    height: 100px;
    border-radius: 50%;
}

.container {
    display: flex;
    justify-content: center;
}
</style>
